import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtTag, AtIcon} from 'taro-ui'
import {View, Block, Text, Image} from '@tarojs/components'
import {user} from '../../utils/user.service'
import {OrderDetail, TicketItem} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {
  GET_ORDER_DETAIL,
  GET_ORDER_TICKET,
  REFUND, RESOURCE_URL
} from '../../constants/api'
import {getHeadTop, GetRequest, vcmonitor} from '../../utils/tools'
import Headercar from "../components/header-car/header-car";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './detail.scss'

interface LogList {
  use_date: string
  check_num: number
  product_name: string
  company: string
}

export default class Detail extends Component {
  tabs = [{title: '订单详情'}, {title: '验证码信息'}]
  state: {
    coupon: boolean
    searchBarTop: number
    orderInfo: OrderDetail | false
    orderTicket: TicketItem[]
    ticketwell: TicketItem[]
    ticketing: TicketItem[]
    ticketed: TicketItem[]
    logList: LogList[]
    refunding: boolean
    backRefund: boolean
    goodDetailUrl: string
    qrcodeimg: string
    pcodeimg: string
    tMore: boolean
    codeShow: boolean
    tabsIndex: number
    ticketWxCode: string
    ticketCode: string
    ticketCanvasId: string
    openGroup: boolean
    importText: string
    assembling_place_list: any
    openAssembling: boolean
    wxCodeType: number
    popTicket: string
    groupTicket: any
    groupIndexs: any
  } = {
    coupon: false,
    searchBarTop: 0,
    pcodeimg: '',
    qrcodeimg: '',
    orderInfo: false,
    orderTicket: [],
    codeShow: false,
    ticketwell: [],
    ticketing: [],
    ticketed: [],
    logList: [],
    backRefund: true,
    refunding: false,
    goodDetailUrl: '',
    tMore: false,
    ticketWxCode: '',
    wxCodeType: 0,
    ticketCode: '',
    tabsIndex: 0,
    openGroup: false,
    importText: '',
    assembling_place_list: [],
    openAssembling: false,
    popTicket: '',
    groupTicket: {},
    groupIndexs: [],
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    this.setState({
      searchBarTop
    })
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const {orderId} = Taro.getCurrentInstance().router.params
    if (!orderId) {
      Taro.showToast({title: '参数错误', icon: 'none'})
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack({
          delta: 1
        })
      }, 1500);
    }
    Taro.showLoading({title: '加载中...'})
    const orderInfo = await http.get<OrderDetail>(GET_ORDER_DETAIL, {orderId})
    if (orderInfo) {
      if (orderInfo.assembling_place) {
        this.setState({
          assembling_place_list: JSON.parse(orderInfo.assembling_place)
        })
      }
    }
    const orderTicket = await http.get<TicketItem[]>(GET_ORDER_TICKET, {orderId})
    this.setState({orderInfo, orderTicket})
    Taro.hideLoading()
  }

  copy() {
    if (this.state.orderInfo) {
      try {
        Taro.setClipboardData({
          data: this.state.orderInfo.order_num
        })
        if (process.env.TARO_ENV === 'h5') {
          Taro.showToast({title: '复制成功'})
        }
      } catch (e) {
        Taro.showToast({title: '复制失败'})
      }
    } else {
      Taro.showToast({title: '复制失败'})
    }
  }

  onCopy(str) {
    try {
      Taro.setClipboardData({
        data: str
      })
      if (process.env.TARO_ENV === 'h5') {
        Taro.showToast({title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  onCopyShow(item) {
    if (item.code_type == 2) {
      Taro.previewImage({
        current: item.ticket, // 当前显示图片的http链接
        urls: [item.ticket] // 需要预览的图片http链接列表
      })
    } else if (item.code_type == 0) {
      this.onCopy(item.ticket)
    } else {
      try {
        Taro.setClipboardData({
          data: item.ticket
        })
        if (process.env.TARO_ENV === 'h5') {
          Taro.showToast({title: '复制成功'})
        }
        this.setState({
          importText: item.ticket
        })
      } catch (e) {
        Taro.showToast({title: '复制失败'})
      }
    }
  }

  refund(e) {
    e.stopPropagation()
    this.setState({refunding: true}, () => {
      Taro.showModal({
        title: '提示',
        content: '确认申请退款？',
        success: async (res) => {
          if (res.confirm) {
            const ret = await http.post(REFUND, {oid: (this.state.orderInfo && this.state.orderInfo.id) || 0})
            if (ret) {
              Taro.showLoading({title: '加载中...'})
              const orderInfo = await http.post<OrderDetail>(GET_ORDER_DETAIL, {orderId: (this.state.orderInfo && this.state.orderInfo.id) || 0})
              const orderTicket = await http.post<TicketItem[]>(GET_ORDER_TICKET, {orderId: (this.state.orderInfo && this.state.orderInfo.id) || 0})
              this.setState({orderInfo, orderTicket})
              Taro.hideLoading()
              Taro.showToast({title: '退款申请提交成功！', icon: 'none'})
            }
          }
          if (res.cancel) {
            this.setState({refunding: false})
          }
        }
      })
    })
  }

  async showCode(item) {
    if (item.is_use < 1 || item.is_use >= 5) {
      this.setState({
        codeShow: true, ticketCode: item.qr_code_url, popTicket: item.ticket
      })
    }
  }

  showImg(current) {
    Taro.previewImage({
      current,
      urls: [current]
    })
  }

  hideCode(e) {
    e.stopPropagation()
    this.setState({
      codeShow: false
    })
  }

  handleClickGroup() {
    const openGroup = this.state.openGroup
    this.setState({
      openGroup: !openGroup
    })
  }

  couponOpen() {
    const coupon = this.state.coupon
    this.setState({
      coupon: !coupon
    })
  }

  render() {
    const {codeShow, searchBarTop, orderInfo, orderTicket, popTicket, backRefund, logList, ticketCode} = this.state
    if (!orderInfo) {
      return
    }
    let goodsGroup: { name: string; num: number; good_id: number }[] = []
    if (orderInfo.goods_group) {
      const goodsGroupRet = JSON.parse(orderInfo.goods_group)
      if (goodsGroupRet && goodsGroupRet.length > 0) {
        goodsGroup = goodsGroupRet
      }
    }
    return (
      <View className='order-warp-root'>
        <GzhAuth />
        <View className='head-bg head-bg-movie' style={`height: ${searchBarTop + 10}Px;`}>
          <Headercar color='white' title='订单详情' tabColor='#fff' backgroundColor='none' bcolor='#fff' />
        </View>
        <View className='order-top'>
          <View className='status'>{orderInfo && orderInfo.status}</View>
          {orderInfo.status == "已退款" && orderInfo.refund_type != undefined && orderInfo.refund_type != 3 &&
          <View className='sms'>
            已退款退至您的{orderInfo.refund_type == 0 ? '微信' : (orderInfo.refund_type == 1 ? '余额账户' : '授信账户')}，请注意查收~
          </View>}
        </View>
        <View className='ticket-box-top'>
          <View className='ticket-top ticket-top-info ticket-top-info-height'>
            <View className='text ticket-top-order min-padding'>{orderInfo.goods_group ? orderInfo.product_name : orderInfo.name}</View>
            <View className='ticket-top-order min-padding'>{orderInfo && orderInfo.order_num}</View>
          </View>
          {orderTicket && orderTicket.length == 1 &&
          <View className='ticket-top-info'>
            <View className='ticket-top-xian' />
            <View className='qrbox'>

              <View
                className={(orderTicket[0].used_check_num || (orderTicket[0].can_check_num && orderTicket[0].is_use > 1 && orderTicket[0].is_use < 5)) ? "onle-ticket filter" : "onle-ticket"}
              >
                {orderTicket[0].is_use > 0 && orderTicket[0].is_use < 5 && <View className='onle-ticket-img'>
                  {orderTicket[0].is_use == 1 &&
                  <Image src={RESOURCE_URL + "/resources/weapp/images/status1.png"} />}
                  {orderTicket[0].is_use == 4 &&
                  <Image src={RESOURCE_URL + "/resources/weapp/images/status4.png"} />}
                  {orderTicket[0].is_use == 2 &&
                  <Image src={RESOURCE_URL + "/resources/weapp/images/status2.png"} />}
                </View>}
                <View className='t_ticket' style='margin-top:60rpx'>取票码:{orderTicket[0].ticket}</View>
                <View className='code-box'>{orderTicket[0].qr_code_url &&
                <Image style='width:400rpx;height:400rpx' className='qrimg'
                  src={orderTicket[0].qr_code_url}
                />}</View>
                <View className='code-shuoming'>
                  {orderTicket[0].qr_code_url && <Text>凭该码取票</Text>}
                </View>
              </View>
            </View>
          </View>
          }
        </View>
        {orderTicket && orderTicket.length > 1 && orderTicket.map(item => <View className='ticket-box-well'
          onClick={this.showCode.bind(this, item)}
          key={item.id}
        >
          <View className='ticket-well-num'>
            <View className='ticket-well-num-box'><Text>取票码:{item.ticket}</Text></View>
          </View>
          <View className='ticket-well-state'>
            {(item.is_use < 1 || item.is_use > 5) && <View>未使用</View>}
            {item.is_use == 5 && <View>部分使用</View>}
            {item.is_use == 4 && <View>已过期</View>}
            {item.is_use == 2 && <View>已失效</View>}
            {item.is_use == 1 && <View>已使用</View>}
            <View className='state'>{item.can_check_num}张</View>
          </View>
        </View>)}
        {logList.length > 0 &&
        <View className='log'>
          <View className='log-title'>
            使用记录
          </View>
          {logList.map((item, index) =>
            <View className='log-item' key={index}>
              <View className='log-date'>{item.use_date}<Text>{item.check_num}张</Text></View>
              <View className='log-date-info'>
                <View className='group-product'>{item.product_name}</View>
                <View className='group-company'>{item.company}</View>
              </View>
            </View>
          )}
        </View>
        }
        {codeShow && <View className='show_code'>
          <View className='show_code_bj' onClick={this.hideCode.bind(this)} />
          <View className='show_code_content'>
            <View className='show_code_box'>
              {ticketCode &&
              <View className='ticketCode' style='width:400rpx;height:400rpx'><Image className='img' src={ticketCode} /></View>}
            </View>
            <View className='show_code_tips'>
              {popTicket && <View className='show_code_ticket'>取票码：{popTicket}</View>}
              <View className='show_code_title'>出示该二维码即可取票</View>
              <View className='show_code_desc'>避免商家网络不佳影响使用，建议截图保存
                在相册</View>
            </View>
            <Image className='close' src={RESOURCE_URL + "/resources/weapp/images/codeOff.png"}
              onClick={this.hideCode.bind(this)}
            />
          </View>
        </View>}
        <View className='content'>
          <View className='head'>
            <View className='title'>订单号: <AtTag onClick={this.copy.bind(this)} circle type='primary'
              size='small'
            >点击可复制</AtTag></View>
            <View className='no' onClick={this.copy.bind(this)}>{orderInfo && orderInfo.order_num}
            </View>
          </View>
          <View className='item'><View className='title'>电影名称:</View><View
            className='text'
          >{orderInfo.goods_group ? orderInfo.product_name : orderInfo.name} </View></View>
          {orderInfo.buy_date && orderInfo.goodsType != 'product' &&
          <View className='item'><View className='title'>可用日期:</View><View
            className='text'
          >{orderInfo && orderInfo.buy_date}</View></View>}
          {orderInfo.validTimeMsg && orderInfo.goodsType != 'product' &&
          <View className='item'><View className='title'>可用时间:</View><View
            className='text'
          >{orderInfo && orderInfo.validTimeMsg}</View></View>}
          {orderInfo.seatName && <View className='item'><View className='title'>座位信息:</View><View
            className='text'
          >{orderInfo && orderInfo.seatName}</View></View>}
          {orderInfo.hallType && <View className='item'><View className='title'>影厅类型:</View><View
            className='text'
          >{orderInfo && orderInfo.hallType}</View></View>}
          {orderInfo.cinemaName && <View className='item'><View className='title'>影院名称:</View><View
            className='text'
          >{orderInfo && orderInfo.cinemaName}</View></View>}
          {orderInfo.cinemaAddress && <View className='item'><View className='title'>影院地址:</View><View
            className='text'
          >{orderInfo && orderInfo.cinemaAddress}</View></View>}
          {orderInfo.duration && <View className='item'><View className='title'>放映时长:</View><View
            className='text'
          >{orderInfo && orderInfo.duration}</View></View>}
          {orderInfo.movie_start && <View className='item'><View className='title'>开场时间:</View><View
            className='text'
          >{orderInfo && orderInfo.movie_start}</View></View>}
          {orderInfo && orderInfo.unit_fee && orderInfo.pay_type != 4 &&
          <View className='item'><View className='title'>商品单价:</View><View
            className='text'
          >¥{orderInfo && orderInfo.unit_fee}</View></View>}
          {goodsGroup && goodsGroup.length > 0 && goodsGroup.map(item => <Block>{item.num > 0 &&
          <View className='item'><View className='title'>{item.name}:</View><View
            className='text'
          >{item.num}</View></View>}</Block>)}
          {!goodsGroup && <View className='item'><View className='title'>购买数量:</View><View
            className='text'
          >{orderInfo && orderInfo.buy_amount}</View></View>}
          <View className='item'><View className='title'>购买人:</View><View
            className='text'
          >{orderInfo && orderInfo.nick_name}</View></View>
          <View className='item'><View className='title'>接收人姓名:</View><View
            className='text'
          >{orderInfo && orderInfo.linkman}</View></View>
          <View className='item'><View className='title'>接收人手机:</View><View
            className='text'
          >{orderInfo && orderInfo.phone}</View></View>
          {orderInfo && orderInfo.address && <View className='item'><View className='title'>接收人地址:</View><View
            className='text'
          >{orderInfo && orderInfo.address}</View></View>}
          {orderInfo && orderInfo.defined_img &&
          <View className='group-title' onClick={this.showImg.bind(this, orderInfo.defined_img)}><Text>图片:</Text><AtIcon
            value='chevron-right' size='15' color='#ccc'
          ></AtIcon></View>}
          {orderInfo && orderInfo.remark && <View className='item'><View className='title'>备注:</View><View
            className='text'
          >{orderInfo && orderInfo.remark}</View></View>}
          {orderInfo.pay_type != 4 && <View className='item'><View className='title'>订单金额:</View><View
            className='text'
          >¥{orderInfo && orderInfo.total_fee}</View></View>}
          {orderInfo && (orderInfo.status == "已付款" || orderInfo.status == "已完成") && orderInfo.pay_type != 4 &&
          <View className='item'><View className='title'>支付方式:</View><View
            className='text'
          >{orderInfo.useAccountPay_name}</View></View>}
          {orderInfo && orderInfo.coupon_nums && orderInfo.coupon_nums.length > 0 &&
          <View className='group' onClick={this.couponOpen.bind(this)}><View className='group-title'>兑换码:<View
            className='text'
          >{orderInfo.coupon_nums[0]}{orderInfo.coupon_nums.length > 1 &&
          <AtIcon value='chevron-right' size='15' color='#ccc'></AtIcon>}</View></View></View>}
          {orderInfo && orderInfo.offpay_date && <View className='item'><View className='title'>支付时间:</View><View
            className='text'
          >{orderInfo && orderInfo.offpay_date}</View></View>}
          {orderInfo && orderInfo.pay_notice_mark && <View className='item'><View className='title'>产品备注:</View><View
            className='text'
          >{orderInfo && orderInfo.pay_notice_mark}</View></View>}
          {orderInfo && orderInfo.site_remark_for_customer &&
          <View className='item'><View className='title'>其他信息:</View><View
            className='text'
          >{orderInfo && orderInfo.site_remark_for_customer}</View></View>}
          {orderInfo && orderInfo.pay_source_name && <View className='item'><View className='title'>订单来源:</View><View
            className='text'
          >{orderInfo && orderInfo.pay_source_name}</View></View>}
        </View>
      </View>
    )
  }
}
